<template>
	<div class="box" ref="mainRight" id="rightCont">
	<!-- 头部图标页面名称 -->
	<div class="main" id="main">
		<div class="header">
			<div class="header-tab">
				<div class="iconTitle">
					<i class="el-icon-blsjxj" style="border-radius: 50%;font-size: 20px;padding: 2px;margin-left: 8px;background-color: #409EFF;color: #fff;"></i>
					<span style="font-weight:400;margin-left: 12px;font-size: 12px;">{{ CatalogueName }}</span>
				</div>
				<div class="tabs">
					<el-tabs v-model="activeName" @tab-click="tabsHandleClick">
						<el-tab-pane label="草稿"   name="0"></el-tab-pane>
						<el-tab-pane label="已提交" name="2"></el-tab-pane>
						<el-tab-pane label="已审核" name="4"></el-tab-pane>
						<el-tab-pane label="已过单" name="5"></el-tab-pane>
						<el-tab-pane label="已冲销" name="6"></el-tab-pane>
					</el-tabs>
				</div>
			</div>
			<!-- btn2 -->
			<div class="header-bottom">
				<!-- 申请科室 -->
				<el-select v-model="ksValue" @clear="clearKs" @change="getputInDep" clearable placeholder="申请科室" size="mini" style="width: 94px;">
					<el-group>
					  <!-- 固定头部 -->
					  <div class="select-header" slot="header" 
					  style="font-size: 12px;font-weight: bold;display: flex;justify-content: space-around;padding: 12px;background-color: #f1f1f1;">
					    <span>编码</span>
					    <span>名称</span>
					  </div>
					  <!-- 选项内容 -->
					  <el-option
					    v-for="item in optionks"
					    :key="item.id"
					    :label="item.title"
					    :value="item.id">
					    <span style="float: left;font-size: 12px">{{ item.code }}</span>
					    <span style="float: right;font-size: 12px">{{ item.title }}</span>
					  </el-option>
					</el-group>
				</el-select>
				<!-- 供货单位 -->
				<el-select v-model="GysValue" @clear="clearGys" clearable placeholder="供货单位" size="mini" style="width: 158px;" @change="getGysValue">
					<el-group>
					  <!-- 固定头部 -->
					  <div class="select-header" slot="header" 
					  style="font-size: 12px;font-weight: bold;display: flex;justify-content: space-around;padding: 12px;background-color: #f1f1f1;">
					    <span>名称</span>
					    <span>许可证号</span>
					  </div>
					  <!-- 选项内容 -->
					  <el-option
					    v-for="item in gysOption"
					    :key="item.id"
					    :label="item.label"
					    :value="item.id">
					    <span style="float: left;font-size: 12px;width:128px;">{{ item.label }}</span>
					    <span style="float: right;font-size: 12px;width:88px;">{{ item.permitNumber }}</span>
					  </el-option>
					</el-group>
				</el-select>
				
				<!-- 时间 -->
				<el-select v-model="dateTimeValue" placeholder="创建时间" size="mini" style="width: 99px;" @change="getDateTime">
					<el-option
					  v-for="item in dateTimeOption"
					  :key="item.id"
					  :label="item.label"
					  :value="item.id">
					  <span style="float: left;font-size: 12px">{{  item.label }}</span>
					</el-option>
				</el-select>
				<!-- dateTimer -->
				<div class="block">
					<el-date-picker v-model="startDate" type="datetime" size="mini" placeholder="选择开始时间" align="right" 
						:picker-options="pickerOptions" @change="startDateHandle"> 
					</el-date-picker>
					<el-date-picker v-model="endDate" type="datetime" style="margin-left: 8px;" size="mini" placeholder="选择结束时间" align="right"
						:picker-options="pickerOptions" @change="endDateHandle">
					 </el-date-picker>
				</div>
				<!-- 查找按钮 -->
				<el-button size="mini" :loading="loading" type="info" @click="found" icon="el-icon-Ssearch">查询</el-button>
				<!-- 重置按钮 -->
				<el-button size="mini" plain type="info" @click="rest">重置</el-button>
			</div>
			<!-- 按钮 -->
			<div class="header-btns">
				<div class="feetBtn">
					<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :disabled="v.disabled"
					:loading="loading" :icon="v.icon" size="mini" @click="feetHandClick(v,i)">{{ v.title }}</el-button>
				</div>
				<div class="headBtn">
					<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini"
					 @click="handClick(v,i)">{{ v.title }}</el-button>
					 <!-- 展开/折叠按钮 -->
					 <el-tooltip :content="isExpanded ? '折叠' : '展开'" placement="top" style="margin-left: 12px;">
					 	<i :class="isExpanded ? 'el-icon-bumenOpen' : 'el-icon-maximize'" 
					 	@click="toggleExpandAll" style="cursor: pointer; margin-right: 8px;"></i>
					 </el-tooltip>
					 <!-- tooltipBtns -->
					 <div class="tooltips" v-for="(item,index) in tooltipBtns" :key="item.title">
						 <!-- 循环图标按钮 -->
						 <el-tooltip :content="item.title" :placement="item.type">
						 	<i :class="item.icon" @click="tooltipsHand(item,index)" style="cursor: pointer; margin-right: 8px;"></i>
						 </el-tooltip>
					 </div>
				</div>
			</div>
		</div>
		<!-- table -->
		<div class="table">
			<el-table
			  ref="table"
			  :data="tableData" 
			  :max-height="tableHeight"
			  highlight-current-row 
			  @current-change="handleCurrentTableChange"
			  @selection-change="handleSelectionChange"
			  @row-contextmenu="handleRightClick"
			  show-summary 
			  :summary-method="getSummaries"
			  :row-key="getRowKeys"
			  :default-expand-all="false"
			>
			<!-- 添加多选列 -->
			<!-- <el-table-column 
			  type="selection" 
			  width="50"
			  align="center">
			</el-table-column> -->
			<!-- 修改展开列 -->
			<el-table-column type="expand" width="50" fixed="left" class-name="custom-expand-column">
				<template slot-scope="props">
				  <div class="expand-content-wrapper" style="height: 60px;">
					<el-descriptions 
					  class="margin-top" 
					  :column="8" 
					  border
					  size="mini"
					>
					<el-descriptions-item label="单据编号">{{ props.row.docNum }}</el-descriptions-item>
					<el-descriptions-item label="业务日期">{{ props.row.busDate }}</el-descriptions-item>
					<el-descriptions-item label="供货单位">{{ props.row.supplierName }}</el-descriptions-item>
					<el-descriptions-item label="申请人">{{ props.row.createName }}</el-descriptions-item>
					<el-descriptions-item label="制单时间">{{ props.row.createTime }}</el-descriptions-item>
					<el-descriptions-item label="合计金额">{{ props.row.totalAmt }}</el-descriptions-item>
					<el-descriptions-item label="审核人">{{ props.row.reviewName }}</el-descriptions-item>
					<el-descriptions-item label="审核时间">{{ props.row.reviewTime }}</el-descriptions-item>
					<el-descriptions-item label="过单人">{{ props.row.passingOrdersName }}</el-descriptions-item>
					<el-descriptions-item label="过单时间">{{ props.row.passingOrdersTime }}</el-descriptions-item>
					<el-descriptions-item label="作废人">{{ props.row.nullifyId }}</el-descriptions-item>
					<el-descriptions-item label="作废时间">{{ props.row.nullifyTime }}</el-descriptions-item>
				  </el-descriptions>
					</div>
				  </template>
			</el-table-column>
			<!-- 表格行rows -->
			<!-- <el-table-column prop="id" label="系统序号"></el-table-column> -->
			<el-table-column prop="docNum" label="单据编号" width="168">
				<template slot-scope="{ row }">
					<span style="color: #00557f;font-weight: bold;">{{ row.docNum }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="busDate" label="业务日期" width="168">
				<template slot-scope="{ row }">
					<span style="font-weight: bold;">{{ row.busDate }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="status" label="状态">
				 <template slot-scope="{ row }">
					<!-- 根据state显示不同的图标 -->
					<div class="stateValue" style="border-radius: 4px;background-color: #e2fff6;text-align: center;color: #004a00;">
						<i :class="statusIconMap[row.state]" :style="{ color: statusColorMap[row.state] }"></i>
						<span>{{ statusMap[row.state] || '未知状态' }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="shedId" label="入库库房">
				 <template slot-scope="{ row }">
					<!-- 根据state显示不同的图标 -->
					<div class="stateValue" style="border-radius: 4px;text-align: center;">
						<i :class="sheIdIconMap[row.shedId]" :style="{ color: sheIdColorMap[row.shedId] }"></i>
						<span>{{ sheIdMap[row.shedId] || '未知状态' }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
			<!-- fixed -->
			<el-table-column fixed="left" label="行号" type="index" width="68" align="center"></el-table-column>
			<!-- edit -->
			<el-table-column fixed="right" label="操作" width="88">
				  <template slot-scope="scope">
					<div class="editbox" v-if="scope.row.state == 0">
						<el-link type="info" @click="handleClickEdit(scope.row)" size="mini" style="font-size: 12px;">修改</el-link>
						<el-link type="danger" @click="handleDelete(scope.row)" size="mini" style="margin-left: 12px;font-size: 12px;">删除</el-link>
					</div>
					<div class="editbox" v-else style="text-align: center;">
						<!-- 根据state显示不同的图标 -->
						<i :class="statusIconMap[scope.row.state]" :style="{ color: statusColorMap[scope.row.state] }"></i>
						<span>{{ statusMap[scope.row.state] || '未知状态' }}</span>
					</div>
				  </template>
				</el-table-column>
			</el-table>

			<!-- 添加右击菜单 -->
			<div v-show="contextMenuVisible" 
			     class="context-menu" 
			     :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}"
			     @click.stop>
			  <div class="menu-item" 
			       :class="{disabled: rightClickedRow && rightClickedRow.state !== 0}"
			       @click="handleMenuDelete">删除</div>
			  <div class="menu-item" @click="handleQuickTransfer">快速调拨</div>
			</div>
		</div>
		
		<!-- feet -->
		<div class="feet">
			<!-- 分页 -->
			<el-pagination
			style="margin: 12px;"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page="pageNum"
			:page-sizes="[20,50,100]"
			:page-size="pageSize"
			:total="totalSize"
			layout="total, sizes, prev, pager, next, jumper"
			background>
			</el-pagination>
		</div>
	</div>
		<!-- 快速调拨对话框 -->
		<div class="fast">
			<el-dialog
			  title="快捷调拨单" 
			  :visible.sync="toPassDialog" 
			  width="40%"
			  custom-class="quick-transfer-dialog"
			  :close-on-click-modal="false"
			>
			  <!-- Header 部分 -->
			  <div class="dialog-header">
			    <div class="warehouse-info">
			      <div class="warehouse-item">
			        <span class="label">当前库房：</span>
			        <el-select 
			          v-model="shedId" 
			          placeholder="请选择收货库房" 
			          size="mini" 
			          style="width: 100%"
			        >
			          <el-option 
			            v-for="item in optionks" 
			            :key="item.id" 
			            :label="item.label" 
			            :value="item.id"
			          ></el-option>
			        </el-select>
			      </div>
			      <div class="warehouse-item">
			        <span class="label">收货库房：</span>
			        <el-select 
			          v-model="phayId" 
			          placeholder="请选择收货库房" 
			          size="mini" 
			          style="width: 100%"
			        >
			          <el-option 
			            v-for="item in optionks" 
			            :key="item.id" 
			            :label="item.label" 
			            :value="item.id"
			          ></el-option>
			        </el-select>
			      </div>
			    </div>
			  </div>
			
			  <!-- Main 部分 - 明细表格 -->
			  <div class="dialog-main" style="margin-top: 12px;">
			    <el-table
			      :data="tableDetailsData"
			      border
			      size="small"
			      style="width: 100%;overflow: hidden;"
			      height="300px"
			      highlight-current-row
			    >
			      <el-table-column
			        prop="drugCode"
			        label="药品编码"
			        width="120"
			        align="center"
			      ></el-table-column>
			      <el-table-column
			        prop="drugName"
			        label="药品名称"
			        width="150"
			        align="center"
			      ></el-table-column>
			      <el-table-column
			        prop="drugSpec"
			        label="规格"
			        width="120"
			        align="center"
			      ></el-table-column>
			      <el-table-column
			        prop="manuLotnum"
			        label="批号"
			        width="120"
			        align="center"
			      ></el-table-column>
			      <el-table-column
			        prop="purcCnt"
			        label="数量"
			        width="128"
			        align="center"
			      ></el-table-column>
			      <el-table-column
			        prop="unt"
			        label="入库单位"
			        width="128"
			        align="center"
			      ></el-table-column>
			      <el-table-column prop="purcType" label="库存类型" align="center">
			        <template slot-scope="{ row }">
			          <span>{{ purcTypeMap[row.purcType] || '未知状态' }}</span>
			        </template>
			      </el-table-column>
				  <el-table-column
				    prop="purcPric"
				    label="成本单价"
				    width="100"
				    align="center"
				  ></el-table-column>
			      <el-table-column
			        prop="purcAmt"
			        label="成本金额"
			        width="100"
			        align="center"
			      ></el-table-column>
				  <el-table-column
				    prop="salePric"
				    label="零售单价"
				    width="100"
				    align="center"
				  ></el-table-column>
			      <el-table-column
			        prop="saleAmt"
			        label="零售金额"
			        width="100"
			        align="center"
			      ></el-table-column>
			      <el-table-column
			        prop="purcCnt"
			        label="库存数量"
			        width="100"
			        align="center"
			      ></el-table-column>
			      <el-table-column
			        label="操作"
			        width="80"
			        align="center"
			      >
			        <template slot-scope="scope">
			          <span @click="removeItem(scope.$index)" style="cursor: pointer;">删除</span>
			        </template>
			      </el-table-column>
			    </el-table>
			  </div>
			
			  <!-- Footer 部分 -->
			  <div class="dialog-footer">
			    <div class="total-info">
			      <span>合计成本金额：{{ computedTotalCostAmount }} 元</span>
			      <span style="margin-left: 20px;">合计零售金额：{{ computedTotalSaleAmount }} 元</span>
			    </div>
			    <div class="action-buttons" style="padding: 20px;text-align:right;">
			      <el-button 
			        type="primary" 
			        @click="confirmTransfer" 
			        size="small" 
			        :disabled="!phayId || tableDetailsData.length === 0"
			      >确认调拨</el-button>
			      <el-button @click="cancelTransfer" size="small">取消</el-button>
			    </div>
			  </div>
			</el-dialog>
		</div>
		<!-- 设置对话框 -->
		<div class="tool">
			<el-dialog title="高级选项设置" :visible.sync="settingDialogVisible" width="30%">
			  <el-form>
				<el-form-item label="是否需要审核">
				    <el-checkbox v-model="quickRefer" disabled></el-checkbox>
				</el-form-item>
			    <el-form-item label="是否快捷调拨">
			      <el-checkbox v-model="quickTransfer"></el-checkbox>
			    </el-form-item>
			  </el-form>
			  <span slot="footer" class="dialog-footer">
			    <el-button @click="settingDialogVisible = false" size="mini">取消</el-button>
			    <el-button type="primary" @click="saveSettings" size="mini">保存</el-button>
			  </span>
			</el-dialog>
		</div>
		<!-- add dialog -->
		<div class="addDiglog">
		<!-- <el-dialog title="新增采购计划" :visible.sync="addDialogVisible" width="68%" :before-close="handleClose"> -->
			<addDiglog ref='sonRef' :parent-method="loadData"></addDiglog>
		<!-- </el-dialog> -->
		</div>
		<!-- 修改 -->
		<div class="editdiglog">
			<!-- <editDiglog ref='editSonRef' @Update="loadData" :parent-method="loadData"></editDiglog> -->
		</div>
		<!-- 审核过单 -->
		<div class="editdiglog">
			<exaDiglog ref='exaRef' @Update="loadData" :parent-method="loadData"></exaDiglog>
		</div>
	</div>

</template>

<script>
	// selfs / props
	import addDiglog from "./addRukuDiglog.vue"; //新增Model
	import exaDiglog from "./exaStoreDiglog.vue"; //审核.过单Model
	
	// selfs / js
	import addForm from './addForm.js' //Form表单
	// xter
	// 接口
	// import { purctcmtablePage,toExaminePurctcmdoc,selectDropDownList,deleteTcm,traMediciList } from "@/api/systemCatalogue/traMedici.js";
	// 接口 快捷调拨
	import { fastTransfer } from "@/api/systemCatalogue/traMedici.js";
	import { purctcmtablePage,deleteTcm,toExaminePurctcmdoc,selectDropDownList,traMediciList,getPurctcmdocPage } from "@/api/systemCatalogue/traMedici.js";
	
	export default{
		inject: ['reload'], // 无痕刷新
		components:{
			addDiglog,exaDiglog
		},
		computed: {
		  // 计算合计成本金额
		    computedTotalCostAmount() {
		      if (!this.tableDetailsData || this.tableDetailsData.length === 0) {
		        return '0.00';
		      }
		      const total = this.tableDetailsData.reduce((sum, item) => {
		        return sum + (Number(item.purcAmt) || 0);
		      }, 0);
		      return total.toFixed(2);
		    },
		    // 计算合计零售金额
		    computedTotalSaleAmount() {
		      if (!this.tableDetailsData || this.tableDetailsData.length === 0) {
		        return '0.00';
		      }
		      const total = this.tableDetailsData.reduce((sum, item) => {
		        return sum + (Number(item.saleAmt) || 0);
		      }, 0);
		      return total.toFixed(2);
		    },
		  // 计算属性判断是否是多选状态
		  isMultipleSelected() {
		    return this.multipleSelection.length > 1;
		  },
		  // 计算属性判断是否是单条选中
		  isSingleSelected() {
		    return this.multipleSelection.length === 1;
		  },
		  // 计算属性判断是否有选中项
		  hasSelection() {
		    return this.multipleSelection.length > 0;
		  }
		},
		data(){
			return{
				// str
				windowWidth:'', //右侧表格动态宽度
				iconComes:'el-icon-shopping-cart-2',
				CatalogueName:'其他入库【中药库】',
				nameTitle:'其他入库【中药库】',
				DropDownedName:'全部单据',
				selectedValue:'',
				selectedValueGys:'', // 供应商选择
				tableHeight:'570', // table的高度，以便超出高度显示滚动条
				currentHeight:'', // 用于计算table的高度，以便超出高度显示滚动条
				// blean
				isExpanded: false, // 控制展开/折叠状态
				// ...高级选项设置
				settingDialogVisible: false,
				quickTransfer: false, // 高级选项 => 快速调拨
				quickRefer: true, // 高级选项 => 需要审核
				loading:false,
				dialogVisible:false,
				showFeetBtn:false,
				gdDialogVisible: false,
				isAllSelected: false, // 新增：是否全选
				// 新增右击菜单属性
				contextMenuVisible: false,
				contextMenuLeft: 0,
				contextMenuTop: 0,
				rightClickedRow: null,
				toPassDialog:false,
				auditStatus:'',
				startDate:'', //开始时间
				endDate:'', //结束时间
				formattedDate: '', // 用于存储格式化后的日期时间
				// number
				state:'', // 状态
				pageNum: 1, //当前页currentPage
				pageSize: 20,
				totalSize: 0, //总条数
				activeName:'a',
				ksValue:'',
				GysValue:'',
				shedId:2,
				phayId:4,
				abc:{},
				dateTimeValue:1, // 时间类型: 1 制单时间,2 过单时间,3 审核时间,4 作废时间 
				undefined:'未知错误！请联系管理员', // 错误提示
				drugValue:'',
				tableDetailsData:[],
				// arr title右侧按钮
				headerBtn:[
				 { title:"刷新", type:"top", icon:"el-icon-refresh" },
				 { title:"打印", type:"", icon:"el-icon-printer" },
				 { title:"高级选项", type:"", icon:"el-icon-lcyt" },
				],
				tooltipBtns:[
				 { title:"导出", type:"top", icon:"el-icon-finished" },
				 // { title:"打印", type:"top", icon:"el-icon-printer" },
				 // { title:"导出", type:"", icon:"el-icon-finished" },
				 { title:"关闭", type:"top", icon:"el-icon-close" },
				],
				selecteds:[
				  { title:"全部单据", command:"a" },{ title:"已提交", command:"b" },{ title:"已审核", command:"c" },
				  { title:"已过单", command:"d" },{ title:"已作废", command:"e" },
				],
				// 添加多选数据
				multipleSelection: [], // 存储选中的行数据
				// 页面默认按钮// 基础按钮配置（始终显示）
				defaultButtons:[
					{ refesh:"refesh", title:"冲销", type:"danger", icon:"el-icon-lszt" },
					// { refesh:"refesh", title:"新增", type:"success", icon:"el-icon-adds" },
					{ refesh:"refesh", title:"提交", type:"primary", icon:"el-icon-finished" },
					{ refesh:"refesh", title:"审核", type:"primary", icon:"el-icon-document-checked" },
					{ refesh:"refesh", title:"过单", type:"primary", icon:"el-icon-sort" },
					{ refesh:"refesh", title:"查看明细", type:"primary", icon:"el-icon-printer" },
				],
				// 最终使用的按钮数组
				feetBtn: [],
				optionks:[{id:2,code:'002',label:'中药库'},{id:4,code:'004',label:'中药房'}],
				dateTimeOption:[
					{id:1,value: '制单时间',label: '制单时间'},{id:2,value: '过单时间',label: '过单时间'},
					{id:3,value: '审核时间',label: '审核时间'},{id:4,value: '作废时间',label: '作废时间'},
				],
				drugOption: [],
				// 单据状态 0 草稿,1 回退提交,2 已提交,3 回退审核,4 已审核,5 已过单,6 已作废'
				statusOption:[
					{id:0,label:'草稿'},{id:1,label:'回退提交'},{id:2,label:'已提交'},{id:3,label:'回退审核'},{id:4,label:'已审核'},{id:5,label:'已过单'},{id:6,label:'已作废'},
				], 
				purcTypeMap: {
					1: '最小单位',
					2: '包装单位',
				},
				gysOption:[],
				options:[{value: '制单时间',label: '制单时间'},{value: '过单时间',label: '过单时间'},{value: '操作时间',label: '操作时间'},{value: '业务日期',label: '业务日期'}],
				currentTable: [],//表格单选
				tableRows:[
					{ name:"供货单位", prop:"supplierName", type:"" },{ name:"供货单号", prop:"supplyCode", type:"" },
					{ name:"发票编号", prop:"purcInvoCodg", nz:"nz" },
					{ name:"入库方式", prop:"putinTypeId", type:"" },{ name:"成本金额", prop:"costAmt", type:"" },{ name:"零售金额", prop:"saleAmt", type:"" },
					{ name:"制单人", prop:"createName", type:"" },{ name:"制单时间", prop:"createTime", type:"" },{ name:"审核人", prop:"reviewName", type:"" },
					{ name:"审核时间", prop:"reviewTime", type:"" },{ name:"过单人", prop:"passingOrdersName", type:"" },{ name:"过单时间", prop:"passingOrdersTime", type:"" },
					{ name:"冲销人", prop:"nullify", type:"" },{ name:"冲销时间", prop:"nullifyTime", type:"" },
				],
				pickerOptions: {
				  shortcuts: [
					{ text: '今天', onClick(picker) { picker.$emit('pick', new Date()); }}, 
					{ text: '昨天', onClick(picker) { const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24);picker.$emit('pick', date);}}, 
					{ text: '一周前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);picker.$emit('pick', date);}},
					{ text: '最近一个月',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);picker.$emit('pick', date);}},
					{ text: '最近三个月',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 90);picker.$emit('pick', date);}},
					{ text: '半年前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 180);picker.$emit('pick', date);}},
					{ text: '去年',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 360);picker.$emit('pick', date);}},
					]
				},
				watch: {
				  tableDetailsData: {
				    handler(newVal) {
				      // 更新合计成本金额
				      this.totalCostAmount = this.computedTotalCostAmount;
				      // 更新合计零售金额
				      this.totalSaleAmount = this.computedTotalSaleAmount;
				    },
				    deep: true
				  }
				},
				
				tableData: [],
				addForm:{}, // 新增参数 => 改状态 form表单 * 
				//props
				//props
				sheIdMap: {
					1: '西药库',
					2: '中药库',
				},
				sheIdIconMap: {
					1: 'el-icon-xy',
					2: 'el-icon-zcy',
				},
				sheIdColorMap: {
					1: '#67C23A',
					2: '#409EFF',
				},
				statusMap: {
					0: '待提交',
					1: '回退提交',
					2: '待审核',
					3: '回退审核',
					4: '待过单',
					5: '已过单',
					6: '已冲销',
					7: '已作废',
				},
				statusIconMap: {
					0: 'el-icon-document',
					1: 'el-icon-top-left',
					2: 'el-icon-check',
					3: 'el-icon-bottom-right',
					4: 'el-icon-document-checked',
					5: 'el-icon-success',
					6: 'el-icon-delete'
				},
				statusColorMap: {
					0: '#909399',
					1: '#67C23A',
					2: '#409EFF',
					3: '#E6A23C',
					4: '#409EFF',
					5: '#409EFF',
					6: '#aa0000',
					7: '#F56C6C',
				},
			}
		},
		mounted() {
			this.addForm = addForm.map(v => {return v })[0]; // Form
			// 获取当前日期时间
			this.getNowDateTime();
			//获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.initButtons(); // 引入全局自定义封装方法
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
			})
				
			// 加载数据源
			this.loadData();
			this.currentHeight = this.$getHeights();
			this.getTableHeight();
			this.getGys();
			this.getDrug();
		},
		methods:{
			async loadData(){
				let res = await purctcmtablePage({
					drugName:this.drugValue,
					state:this.state, // 状态
					startDate:this.startDate, //开始结束时间
					endDate:this.endDate,
					id:this.GysValue, // 供应商
					shedId:this.ksValue,// 申请科室 => 库房序号
					type:this.dateTimeValue,// 时间类型
					pageNum:this.pageNum,
					pageSize:this.pageSize,
				});
				this.loading = true;
				setTimeout(()=>{	
					if(res.code === 200){
						this.tableData = res.data.content;
						this.totalSize = res.data.totalSize;
						this.loading = false;
					}else{
						// this.$message({ type: 'error', message: res.message });
						this.tableData = [];
						this.loading = false;
					}
				},888)
			},
			// 权限按钮
			initButtons() {
			    // 获取当前路由路径
			    const currentPath = this.$route.path;
			    // 获取路由对应的权限按钮
			    const routeButtons = this.$getRouteButtons(currentPath);
				console.log(routeButtons,'routeButtonsrouteButtons');
			    // 合并到现有按钮数组
			    this.feetBtn = this.$mergeButtons(this.defaultButtons, routeButtons);
				console.log(this.feetBtn,'feetBtnfeetBtn');
			},
			found(){
				// console.log(this.GysValue ,'this.GysValue this.GysValue ');
				this.loadData();
			},
			// 供应商选择
			getGysValue(val){
				console.log(this.GysValue ,'this.GysValue this.GysValue ');
				// this.loadData();
			},
			// 申请科室选择
			getputInDep(val){
				// console.log(this.GysValue ,'this.GysValue this.GysValue ');
				// this.loadData();
			},
			// 药品选择
			getDrugName(val){
				// console.log(this.drugValue ,'this.GysValue this.GysValue ');
				// this.loadData();
			},
			// 时间类型
			getDateTime(){
				// this.loadData();
			},
			// 添加多选变化事件
			handleSelectionChange(val) {
			  // this.multipleSelection = val;
			  // // 判断是否全选
			  // this.isAllSelected = val.length > 0 && val.length === this.tableData.length;
			  
			  // // 如果有选中项，设置当前行为第一个选中项
			  // if (val.length > 0) {
			  //   this.$nextTick(() => {
			  //     this.$refs.table.setCurrentRow(val[0]);
			  //   });
			  // } else {
			  //   this.$refs.table.setCurrentRow(null);
			  // }
			  
			  // this.updateButtonStates();
			},
			// 更新状态
			updateButtonStates() {
			    this.feetBtn = this.feetBtn.map(button => {
			      const isMultiSelect = this.multipleSelection.length > 1 || this.isAllSelected;
			      
			      if (isMultiSelect) {
			        return {
			          ...button,
			          disabled: !(button.title == '冲销' || button.title == '提交' || button.title == '审核' || button.title == '过单')
			        };
			      }
			      
			      return {
			        ...button,
			        disabled: false
			      };
			    });
			},
			// 用于计算table的高度，以便超出高度显示滚动条
			getTableHeight(){
				let headerHeight = this.currentHeight.mainHeight
				let feetHeight = this.currentHeight.feetHeight
				let lastHeight = this.currentHeight.lastHeight
				this.tableHeight = this.currentHeight.rightContentHeight - feetHeight * 3
				console.log(this.tableHeight,'this.tableHeightthis.tableHeight');
			},
			// 选项卡切换事件
			tabsHandleClick(tab, event) {
				console.log(tab, tab.label);
				if(tab.name == '0'){
					this.state = 0;
					this.loadData();
				}else if(tab.name == '2'){
					this.state = 2;
					this.loadData();
				}else if(tab.name == '4'){
					this.state = 4;
					this.loadData();
				}else if(tab.name == '5'){
					this.state = 5;
					this.loadData();
				}else if(tab.name == '6'){
					this.state = 6;
					this.loadData();
				}
			},
			async getGys(){
				// 供应商下拉列表
				let rs = await selectDropDownList()
				this.gysOption = rs.data.content.map(obj => {
				  // 将 name 替换为 label，并保留其他字段
				  return { label: obj.supplierName , ...obj };
				});
			},
			// 药品下拉选择框 => 中药
			async getDrug(){
				let res = await traMediciList()
				console.log(res.data.content)
				this.drugOption = res.data.content.map(obj => {
				  // 将 name 替换为 label，并保留其他字段
				  return { label: obj.name , ...obj };
				});
			},
			// 计算激活步骤（关键逻辑）
			calcActive(state) {
			  // 状态码与步骤索引的映射关系 => 状态0对应第1个步骤（索引从1开始）
			  const stateMap = { 0:1, 1:2, 2:3, 3:4, 4:5, 5:6, 6:7 }
			  // 返回当前状态对应的步骤索引 如果找不到则默认为0（不激活任何步骤）
			  return stateMap[state] || 0
			  // 或者更简单的数学计算（如果状态码是连续数字）： return Math.min(state + 1, this.statusOption.length)
			},
			// 开始时间变化值
			startDateHandle(value) {
				if (value) {
					// 使用 JavaScript 的 Date 对象格式化日期
					this.startDate = this.formatDate(value);
					// this.loadData();
					this.getTableHeight();
				} else {
					this.startDate = '';
				}
			},
			// 结束时间变化值
			endDateHandle(value){
				if (value) {
				  // 使用 JavaScript 的 Date 对象格式化日期
				  this.endDate = this.formatDate(value);
				  // this.loadData();
				  this.getTableHeight();
				} else {
					this.endDate = '';
				}
			},
			// 处理右击事件
			  handleRightClick(row, column, event) {
			    event.preventDefault(); // 阻止默认右键菜单
			    this.rightClickedRow = row;
			    
			    // 设置菜单位置
			    this.contextMenuLeft = event.clientX;
			    this.contextMenuTop = event.clientY;
			    this.contextMenuVisible = true;
			    
			    // 点击其他地方关闭菜单
			    document.addEventListener('click', this.closeContextMenu);
			  },
			  
			  // 关闭右击菜单
			  closeContextMenu() {
			    this.contextMenuVisible = false;
			    document.removeEventListener('click', this.closeContextMenu);
			  },
			  
			  // 处理菜单删除
			  handleMenuDelete() {
			    if (this.rightClickedRow) {
			      this.$confirm("此操作将永久删除该条入库数据, 是否继续?", "提示", {
			        confirmButtonText: "确定",
			        cancelButtonText: "取消",
			        type: "warning",
			      })
			        .then(async() => {
			          // 状态 => 作废 
			          this.addForm.id = this.rightClickedRow.id;
			          let result = await deleteBy({ ids: this.rightClickedRow.id });
			          if (result.code === 200) {
			            this.$message({ type: 'success', message: result.message });
			            this.loadData(); // 更新数据驱动
			          } else {
			            this.$message.error(result.message)
			          }
			        })
			        .catch(() => {
			          this.$message({ type: "info",message: '已取消'});
			        });
			    }
			    this.closeContextMenu();
			  },
			  
			  // 处理快速调拨
			  async handleQuickTransfer() {
			    if (!this.rightClickedRow) {
			      this.closeContextMenu();
			      return;
			    }
			    
			    try {
			      // 重置合计金额
			      this.resetTotals();
			      
			      // 获取调拨数据
			      this.getDataId = this.rightClickedRow.id;
			      await this.getData();
			      
			      // 打开调拨对话框
			      this.toPassDialog = true;
			      
			      this.$message({
			        type: 'success',
			        message: '已加载调拨数据'
			      });
			    } catch (error) {
			      console.error('快速调拨出错:', error);
			      this.$message.error('加载调拨数据失败');
			    } finally {
			      this.closeContextMenu();
			    }
			  },
			  
			  // 获取调拨数据
			  async getData() {
			    try {
			      let res = await getPurctcmdocPage({id: this.getDataId});
			      this.tableDetailsData = res.data.tcmDocDetails || [];
			      this.abc = {
			        ...res.data,
			        tcmDocDetails: this.tableDetailsData,
			        phayId: this.phayId // 确保有目标库房ID
			      };
			    } catch (error) {
			      console.error('获取药品详情失败:', error);
			      throw error;
			    }
			  },
			  
			  // 确认调拨
			  async confirmTransfer() {
			    if (!this.phayId) {
			      this.$message.warning('请选择收货库房');
			      return;
			    }
			    
			    try {
			      this.abc.phayId = this.phayId;
			      let result = await fastTransfer(this.abc);
			      
			      if (result.code === 200) {
			        this.$message({ 
			          type: 'success', 
			          message: result.message 
			        });
			        this.toPassDialog = false;
			        this.loadData(); // 刷新数据
			      } else {
			        this.$message.error(result.message);
			      }
			    } catch (error) {
			      console.error('调拨出错:', error);
			      this.$message.error('调拨操作失败');
			    }
			  },
			  
			  // 取消调拨
			  cancelTransfer() {
			    this.toPassDialog = false;
			    this.$message.info('已取消调拨操作');
			  },
			  
			  // 移除调拨项
			  removeItem(index) {
			    this.tableDetailsData.splice(index, 1);
			    this.$message.success('已移除该药品');
			  },
			  resetTotals() {
			      this.totalCostAmount = '0.00';
			      this.totalSaleAmount = '0.00';
			  },
			// table合计行
			getSummaries(param) {
				const { columns, data } = param;
				const sums = [];
				columns.forEach((column, index) => {
				  if (index === 1) {
					sums[index] = '总计：';
					return;
				  }else if(index != 9 && index != 10){
					sums[index] = '';
					return;
				  }
				  const values = data.map(item => Number(item[column.property]));
				  if (!values.every(value => isNaN(value))) {
					sums[index] = values.reduce((prev, curr) => {
					  const value = Number(curr);
					  if (!isNaN(value)) {
						return prev + curr;
					  } else {
						return prev;
					  }
					}, 0);
					sums[index] += '（RMB）';
				  } else {
					sums[index] = '';
				  }
				});
				return sums;
			},
			// 修改原有的handleCurrentTableChange方法
			handleCurrentTableChange(val) {
			  this.currentTable = val;
			  // 如果是单选，更新多选数组
			  if (val) {
			    // 找到当前行在表格数据中的索引
			    const index = this.tableData.findIndex(item => item.id === val.id);
			    // 设置该行的选中状态
			    this.$nextTick(() => {
			      this.$refs.table.toggleRowSelection(this.tableData[index], true);
			    });
			    this.multipleSelection = [val];
			  } else {
			    this.multipleSelection = [];
			  }
			  this.updateButtonStates();
			},
			// 循环图标事件
			tooltipsHand(v){
				console.log(v);
				if(v.title == '导出' || v.title.includes('导出')){
					this.$message.error('导出为Excel，Fail!');
				}else if(v.title == '关闭' || v.title.includes('关闭')){
					// 关闭当前页
					setTimeout(() =>{
						window.history.back();
					},888)
				}
			},
			// 展开/折叠所有行
			toggleExpandAll() {
			  // 切换状态
			  this.isExpanded = !this.isExpanded;
			  
			  // 获取表格实例
			  const table = this.$refs.table;
			 //  if(this.tableData.length === 0){
				// // 显示提示信息
				// this.$message({ type: 'success', message: '当前表格暂无数据' });
			 //  }
			  // 根据当前状态展开或折叠所有行
			  this.tableData.forEach(row => {
			    table.toggleRowExpansion(row, this.isExpanded);
			  });
			  // 显示提示信息
			  // this.$message({ type: 'success', message: this.isExpanded ? '已展开所有行' : '已折叠所有行' });
			},
			// 草稿编辑
			handleClickEdit(row){
				row.nameTitle = '编辑'
				console.log(row);
				if(row.state == 0){
					this.$refs.sonRef.open(row) //打开编辑Model
				}else{
					this.$message.error('只有草稿单据才能被修改!');
				}
			},
			// 草稿删除
			handleDelete(row) {
				if(row.state == 0){
					this.$confirm("确定删除此单据吗?", "提示", {
					  confirmButtonText: "确定",
					  cancelButtonText: "取消",
					  type: "warning",
					})
					  .then(async() => {
						// 状态 => 作废 
						this.addForm.id = row.id;
						let result = await deleteTcm({ ids: row.id });
						if (result.code === 200) {
							this.$message({ type: 'success', message: result.message });
							this.loadData(); // 更新数据驱动
						} else {
							this.$message.error(result.message)
						}
					  })
					  .catch(() => {
						this.$message({ type: "info",message: '已取消'});
					  });
				}else{
					this.$message.error('只有草稿单据才能被删除!');
				}
			},
			// 当前日期时间
			formatDate(date) {
			      const year = date.getFullYear();
			      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
			      const day = String(date.getDate()).padStart(2, '0');
			      const hours = String(date.getHours()).padStart(2, '0');
			      const minutes = String(date.getMinutes()).padStart(2, '0');
			      const seconds = String(date.getSeconds()).padStart(2, '0');
			      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			// 将当前日期时间设置为夜晚十一点五十九分
			getNowDateTime(){
				// 获取当前日期时间
				const now = new Date();
				// 格式化日期时间
				// 将时间设置为凌晨十二点
				const midnight = new Date(now);
				midnight.setHours(0, 0, 0, 0);
				this.startDate = this.formatDate(midnight);
				// 将时间设置为夜晚十一点五十九分
				const evening = new Date(now);
				evening.setHours(23, 59, 0, 0);
				this.endDate = this.formatDate(evening);
			},
			// 时间处理
			changDate(val){
				let i = this.idx
				switch(i) {
					case 5:
					function formatDate(date) {
					  const year = date.getFullYear();
					  const month = (date.getMonth() + 1).toString().padStart(2, '0');
					  const day = date.getDate().toString().padStart(2, '0');
					  return `${year}-${month}-${day}`;
					}
					const now = new Date();
					this.addForm.busDate = formatDate(val);
				}
			},
			getRowKeys(row) {
			    return row.id; // 使用行的唯一标识作为key
			},
			// 重置按钮
			rest(){
				this.ksValue = '';
				this.GysValue = '';
				this.drugValue = '';
				this.startDate = '';
				this.endDate = '';
			},
			GysSelected(){
				this.loadData();
			},
			// 打印按钮点击事件
			handlePrint() {
			  this.$confirm('请选择打印方式', '打印设置', {
			    confirmButtonText: 'Lodop打印',
			    cancelButtonText: '浏览器打印',
			    type: 'warning'
			  }).then(() => {
			    // 用户选择Lodop打印
				console.log('用户选择Lodop打印');
			    this.printWithLodop();
			  }).catch(() => {
			    // 用户选择浏览器打印
			    // this.printWithBrowser()
				console.log('用户选择浏览器打印');
			  })
			},
			// 使用Lodop打印并设计
			printWithLodop() {
				  // 准备表格数据
				  const tableData = this.tableData.map(item => {
				    return {
				      ...item,
				      // 添加任何需要转换的字段
				    };
				  });
				  
				  // 准备当前选中行数据
				  const currentTable = this.currentTable;
				  
				  this.$router.push({
				    path: '/PrintTemplateDesigner',
				    query: {
				      tableData: JSON.stringify(tableData),
				      currentTable: JSON.stringify(tableData),
				      templateName: this.CatalogueName
				    }
				});
			},
			// 清空科室选项
			clearKs(){
				this.ksValue = '';
				// this.loadData();
			},
			// 清空供货单位选项
			clearGys(){
				this.GysValue = '';
				// this.loadData();
			},
			// 清空药品名称选项
			clearDrug(){
				this.drugValue = '';
				// this.loadData();
			},
			 // 重置选中状态
			  resetSelection() {
			    this.currentTable = [];
			    this.$refs.table.setCurrentRow(null);
			  },
			  
			  // 刷新数据
			  refreshData() {
			    this.resetSelection();
			    this.loadData();
			  },
			// 打开设置对话框
			openSettings() {
			  // 从会话存储中读取设置
			  const savedSetting = sessionStorage.getItem('quickTransfer');
			  this.quickTransfer = savedSetting ? JSON.parse(savedSetting) : false;
			  this.settingDialogVisible = true;
			  
			  const savedSettingRefer = sessionStorage.getItem('quickRefer');
			  this.quickRefer = savedSetting ? JSON.parse(savedSettingRefer) : true;
			  this.settingDialogVisible = true;
			},
			// 保存设置
			saveSettings() {
			  // 保存到会话存储
			  sessionStorage.setItem('quickTransfer', this.quickTransfer);
			  sessionStorage.setItem('quickRefer', this.quickRefer);
			  this.settingDialogVisible = false;
			  this.$message.success('设置已保存');
			}, 
			// headers commond
			handleCommand(command) {
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  this.auditStatus = ''
				  this.DropDownedName = '全部单据'
				  this.loadData();
				  break;
				case 'b':
				  // 处理b的逻辑
				  this.auditStatus = 2
				  this.DropDownedName = '已提交'
				  this.loadData();
				  break;
				case 'c':
				  // 处理b的逻辑
				  this.auditStatus = 4
				  this.DropDownedName = '已审核'
				  this.loadData();
				  break;
				// ... 其他 case
				case 'd':
				  // 处理b的逻辑
				  this.auditStatus = 5
				  this.DropDownedName = '已过单'
				  this.loadData();
				  break;
				case 'e':
				  // 处理e的逻辑
				  this.auditStatus = 6
				  this.DropDownedName = '已作废'
				  this.loadData();
				  break;
			  }
			},
			// 步骤
			handClick(v,i) {
				 // i event
				  // 处理逻辑 => 打印
				if(v.title == '打印' || v.title.includes('打印')){
					if(!this.currentTable || this.currentTable.length === 0){
					  this.$message({ type: 'warning', message: '请先单击选择一条数据'});
					} else if(this.currentTable.state != 5) {
					  this.$message({ type: 'error', message: '只能打印已过单的数据!'});
					} else {
					  this.currentTable.name = '打印'
					  this.$refs.exaRef.openModel(this.currentTable)
					}
				}
				// 处理逻辑 => 页面刷新
				else if(v.title == '刷新' || v.title.includes('刷新')){
					this.loading = true;
					setTimeout(() => {
						this.reload();
						this.$message({type:'success',message:'已刷新'})
						this.loading = false;		
					}, 1500)
				}
				// 处理逻辑 => 高级选项设置
				else if(v.title == '高级选项' || v.title.includes('高级')){
					this.openSettings();
				}
			},
			feetHandClick(v,i){
				// 获取当前操作按钮
				const button = this.feetBtn[i];
				// 如果按钮被禁用，直接返回
				if (button.disabled) {
					this.$message.warning('当前操作不可用');
					return;
				}
				// 处理逻辑 => 新增
				if(v.title == '新增' || v.title.includes('新增')){
					// 处理索引2的逻辑 => 新增 -> 调用子组件
					this.nameTitle = '新增'
					this.$refs.sonRef.open(this.nameTitle);
				}
				// 处理逻辑 => 修改
				else if (v.title == '修改' || v.title.includes('修改')){
					// 处理索引1的逻辑 => 修改
					if(this.currentTable.length === 0){
						this.$message({ type: 'warning', message: '请先选择一条数据'});
					}else if(this.currentTable.state != 0){
						this.$message({ type: 'error', message: '只能修改草稿数据！'});
					}else{
						this.currentTable.nameTitle = '修改'
						console.log(this.currentTable,'this.currentTable');
						this.$refs.sonRef.open(this.currentTable);
					}
				}
				// 处理逻辑 => 冲销
				else if (v.title == '冲销' || v.title.includes('冲销')){
					if(this.currentTable.length === 0){
						this.$message({ type: 'warning', message: '请先单击选择一条数据'});
					}else if(this.currentTable.state != 5){
						this.$message({ type: 'error', message: '只能冲销已过单的数据！'});
					}else{
						if(this.currentTable){
							this.$confirm("确定需要冲销选中的单据吗?", "提示", {
							  confirmButtonText: "确定",
							  cancelButtonText: "取消",
							  type: "warning",
							})
						  .then(async() => {
							// 状态 => 冲销 
							this.addForm.id = this.currentTable.id;
							this.addForm.state = 6;
							let result = await toExaminePurctcmdoc({
								id:this.addForm.id,
								state: this.addForm.state
							})
							if (result.code === 200) {
								this.$message({ type: 'success', message: result.message});
								this.loadData(); // 更新数据驱动
							} else {
								this.$message.error(result.message)
							}
						  })
						  .catch(() => {
							this.$message({ type: "info",message: '已取消'});
						  });
						}
					}
				}
				// 处理逻辑 => 查看
				else if(v.title == '查看' || v.title.includes('查看')){
					if(this.currentTable.length === 0){
						this.$message({ type: 'warning', message: '请先单击选择一条数据'});
					}else{
						this.currentTable.name = '查看其他入库明细'
						this.$refs.exaRef.openModel(this.currentTable)
					}
				}
				// 处理逻辑 => 提交
				else if(v.title == '提交' || v.title.includes('提交')){
					if(this.currentTable.length === 0){
						this.$message({ type: 'warning', message: '请先单击选择一条数据'});
					}else if(this.currentTable.state != 0){
						this.$message({ type: 'error', message: '只能提交草稿数据！'});
					}else{
						this.currentTable.name = '草稿'
						this.$refs.exaRef.openModel(this.currentTable)
					}
				}
				// 处理逻辑 => 审核
				else if(v.title == '审核' || v.title.includes('审核')){
					if(this.currentTable.length === 0){
						this.$message({ type: 'warning', message: '请先单击选择一条数据'});
					}else if(this.currentTable.state != 2){
						this.$message({ type: 'error', message: '只能审核已提交的数据！'});
					}else{
						this.currentTable.name = '审核'
						this.$refs.exaRef.openModel(this.currentTable)
					}
				}
				// 处理逻辑 => 过单
				else if(v.title === '过单' || v.title.includes('过单')){
					if(this.currentTable.length === 0){
						this.$message({ type: 'warning', message: '请先单击选择一条数据'});
					}else if(this.currentTable.state != 4){
						this.$message({ type: 'error', message: '只能过单已审核的数据！'});
					}else{
						this.currentTable.name = '过单'
						this.$refs.exaRef.openModel(this.currentTable)
					}
				}
				// 处理逻辑 => 关闭
				else if(v.title === '关闭' || v.title.includes('关闭')){
					setTimeout(() =>{
						window.history.back();
					},888)
				}
				// 处理逻辑 => 未知错误
				else{
					this.$message({ type: 'danger', message: this.undefind });
				}
				// i event
			},
			// db events
			// col 里面包含了表头字段和名称，list 是表格数据
			columnWidth(col, list) {
			  let prop = col.prop,lab = col.lab;
			  let width = 20; // 设定一个最小值
			  let maxlenStr = ""; // 最长字符串
			  for (let info of list) {
				if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
			  }
			  width = Math.max(width, len(lab), len(maxlenStr));
			  // 表格自带的内边距(20px) 自调
			  return width + 20; // 这里加了 12px
			  function len(str) {
				// 实际分配长度可根据需要自行调整
				let length = 12;
				for (const char of str + "") {
				  // 英文小写字符 8px
				  if ("a" <= char && char <= "z") length += 8;
				  // 数字
				  else if (Number.isFinite(Number(char))) length += 12;
				  // 英文大写字符 8px
				  else if ("A" <= char && char <= "Z") length += 8;
				  // 中文字符 28px
				  else if (char >= "\u4e00" && char <= "\u9fa5") length += 22;
				  // 其他 8px
				  else length += 12;
				}
				return length;
			  }
			},
			// addDiglog Close
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					done();
				  })
				  .catch(_ => {
				});
			},
			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
				this.windowWidth = window.innerWidth - 188;
			},
		},
		filters: {
		formatTime(timestamp) {
		  if (!timestamp) return 'N/A'
		  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
		}
		},
	}
</script>

<style lang="less" scoped>
	/deep/ .el-tabs__item{
		font-size: 12px;
	}
	/deep/ .el-tabs__header{
		margin: 0px;
	}
	.box{
		display: flex;
		flex-direction: column;
		height: calc(100vh - 64px); // 减去导航栏高度
		width: 100%;
		overflow: hidden;
		.main {
			flex: 1;
		    display: flex;
		    flex-direction: column;
		    overflow: hidden;
		.header{
			flex-shrink: 0; /* 防止header被压缩 */
			background-color: #fff;
			.header-tab{
				display: flex;
				border-bottom: 1px solid #dcdfe6;
				align-items: center;
				.iconTitle{
					display: flex;
					align-items: center;
				}
				.tabs{
					padding-left: 8px;
				}
			}
			.header-bottom{
				background-color: #fff;
				/deep/ .el-select>.el-input{
					height: 28px;
					line-height: 28px;
				}
				gap:8px;
				display: flex;
				align-items: center;
				justify-content: start;
				width: 100%;
				height: 40px;
				line-height: 40px;
				flex-wrap: wrap;
				.main-icon-b{
					display: flex;
					align-items: center;
					padding: 12px;
					width: 100%;
					margin-left: 12px;
				}
				.chose{
					span{
						border: 1px solid #000;
					}
				}
			}
			.header-btns{
				display: flex;
				justify-content: space-between;
				height: 40px;
				padding: 8px;
				line-height: 60px;
				align-items: center;
				background-color: #f1f1f1;
				.headBtn{
					display: flex;
					align-items: center;
				}
				.feetBtn{
					display: flex;
					align-items: center;
				}
			}
		}
		.table{
			flex: 1;
			overflow: hidden;
			// background-color: #00557f;
			/* 添加右击菜单样式 */
			.context-menu {
			  position: fixed;
			  z-index: 9999;
			  background-color: #fff;
			  border: 1px solid #dcdfe6;
			  border-radius: 4px;
			  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
			  padding: 5px 0;
			  min-width: 120px;
			.menu-item.disabled {
				color: #c0c4cc;
				cursor: not-allowed;
				background-color: #f5f7fa;
				
				&:hover {
				  background-color: #f5f7fa;
				  color: #c0c4cc;
				}
			  }
			}
			
			.menu-item {
			  padding: 8px 15px;
			  font-size: 12px;
			  color: #606266;
			  cursor: pointer;
			}
			
			.menu-item:hover {
			  background-color: #ecf5ff;
			  color: #409eff;
			}
			.stateValue{
			    display: flex;
			    align-items: center;
			    justify-content: center;
			    background-color: var(--primary-color, #409EFF) !important;
			    color: var(--text-color, #304156) !important;
			    border: 1px solid var(--text-color, #304156) !important;
			  }
			/deep/ .el-table {
				flex: 1;
				display: flex;
				flex-direction: column;
				width: 100%;
				opacity: .8;
				height: 100% !important; /* 强制表格高度填充容器 */
			    // height: 100% !important;
				.el-table__header-wrapper {
				  flex-shrink: 0;
				}		
				.el-table__footer-wrapper {
				  position: sticky;
				  bottom: 0;
				  background-color: #f5f7fa;
				  z-index: 1;
				  box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1);
				}
			    /* 确保表格主体可以滚动 */
				.el-table__body-wrapper {
				  overflow-y: auto;
				  // overflow-x: hidden;
				}
				
				/* 处理展开行高度 */
				.el-table__expand-column {
				  .cell {
					padding: 0;
				  }
				}
			}
			/deep/ .el-table .cell{
			}
			/deep/ .el-table th{
				color: #2d2d2d;
				font-weight: bold;
				font-size: 12px;
				height: 18px;
				line-height: 18px;
			}
			/deep/ .el-table th.el-table__cell>.cell{
				border-right: 2px solid #ececec;
				height: 18px;
				line-height: 18px;
			}
			/deep/ .el-table td.el-table__cell div{
				font-size: 12px;
				height: 18px;
				line-height: 18px;
			}
			// padding: 16px;
			/* 自定义高亮颜色 */
			::v-deep .el-table__body tr.current-row > td {
			  background-color: #55aaff !important;
			  color: #f9f9f9; /* 可选：修改文字颜色 */
			}
		}
		
		.feet {
		  flex-shrink: 0; /* 防止footer被压缩 */
		  height: 40px;
		  display: flex;
		  justify-content: flex-end;
		  align-items: center;
		  padding: 0 20px;
		  // background-color: #f5f7fa;
		  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		  z-index: 10;
		  
		  /deep/ .el-pagination {
			margin: 0 !important;
		  }
		}
		
		}
		// 快速调拨model
		.fast{
			/deep/ .el-dialog__header{
				padding: 4px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn{
				top: 10px;
			}
			/deep/ .el-dialog__body{
				padding: 10px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-table .cell{
				font-size: 12px;
				font-weight: 400;
				color: #0c0c0c;
				text-align: left;
			}
			/deep/ .el-table th{
				color: #2d2d2d;
				font-weight: bold;
				font-size: 12px;
				height: 18px;
				line-height: 18px;
			}
			/deep/ .el-table th.el-table__cell>.cell{
				border-right: 2px solid #ececec;
				height: 18px;
				line-height: 18px;
				display: flex;
				align-items: center;
			}
			/deep/ .el-table td.el-table__cell div{
				font-size: 12px;
				height: 18px;
				line-height: 18px;
			}
			.dialog-header{
				
			}
			.warehouse-info{
				display: flex;
				justify-content: space-between;
			}
			.warehouse-item{
				display: flex;
				span{
					width: 99px;
				}
			}
		}
	}
</style>